package blog.controller.admin;


import blog.entity.Admin;
import blog.entity.UserInfo;
import blog.service.*;
import blog.util.TimeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author StarryX
 * @since 2020-10-01
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;


    //必须配置路径跳转，否则不会自己跳转到模板引擎渲染的页面
    @GetMapping({"/login"})
    public String login() {
        return "admin/login";
    }

    //必须配置路径跳转，否则不会自己跳转到模板引擎渲染的页面
    @GetMapping({"/test"})
    public String test() {
        return "admin/test";
    }

    //访问管理员首页
    //类似目录跳转，并将总分类数，总博客数，总友情链接数，总标签数，总评论数返回给前端
    @GetMapping({"", "/", "/index", "/index.html"})
    public String index(HttpServletRequest request) {
        request.setAttribute("path", "index");
        request.setAttribute("blogCount", blogService.count());
        request.setAttribute("tagCount", tagService.count());
        request.setAttribute("commentCount", commentService.count());
        request.setAttribute("path", "index");      //用于侧边栏（此处是根据传来的 path 判断用户在使用那个侧边栏模块，并点亮该模块，否则是灰色）
        return "admin/index";
    }

    //访问登录页面
    //todo: 首页中添加一个登录的按钮，其访问路径为 “ /toLogin ”, 记得将狂神社区的登录社区拿来用
    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }


    @GetMapping("/profile")
    //系统设置（修改用户名，密码等）
    public String profile(HttpServletRequest request) {
        UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
        if (loginUserInfo == null) {
            return "admin/login";
        }
        request.setAttribute("path", "profile");
        //todo: 这里在修改密码板块中删除了修改“登录名称”的功能，到时候在页面中记得把对应代码去掉
        request.setAttribute("nickName", loginUserInfo.getNickName());
        return "admin/profile";
    }

    @PostMapping("/profile/password")
    @ResponseBody
    public String passwordUpdate(HttpServletRequest request,
                                 @RequestParam("newPassword") String newPassword) {
        if (StringUtils.isEmpty(newPassword)) {
            return "参数不能为空";
        }
        //todo: 这里既然登录成功了，就不用输入原密码，记得到时候删除对应代码
        UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
        Admin loginAdmin = adminService.getOne(new QueryWrapper<Admin>().eq("info_id", loginUserInfo.getId()));
        Admin admin = new Admin();
        admin.setId(loginAdmin.getId());
        admin.setPassword(new BCryptPasswordEncoder().encode(newPassword));
        admin.setUpdateTime(TimeUtils.getTime());
        if (adminService.updateById(admin)) {
            //修改成功后清空session中的数据，前端控制跳转至登录页
            return "success";
        }else{
            return "error";     //回到修改页面，显示错误信息
        }
        //todo: 这里记得在前端页面添加错误信息
    }

    @PostMapping("/profile/name")
    @ResponseBody
    public String nameUpdate(HttpServletRequest request,
                             @RequestParam("nickName") String nickName) {
        if (StringUtils.isEmpty(nickName)) {
            return "参数不能为空";
        }
        UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
        UserInfo userInfo = new UserInfo();
        userInfo.setNickName(nickName);
        userInfo.setId(loginUserInfo.getId());
        userInfo.setUpdateTime(TimeUtils.getTime());
        if (userInfoService.updateById(userInfo)) {
            return "success";
        } else {
            return "修改失败";
        }
    }
}

